import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, message, Modal, Select } from 'antd';
import React, { useRef, useState } from 'react';
import type { AddPermissionBean, PermissionItem, UpdatePermissionBean } from './data';
import {
  addPermission,
  deletePermission,
  editPermission,
  pageQueryPermissionList,
} from './service';
import AddFrom from './components/AuthPermissionAddForm';
import AuthPermissionEditForm from './components/AuthPermissionEditForm';
import { SUCCESS_CODE } from '@/utils/request';
import { useModel } from 'umi';

const TableList: React.FC<{}> = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser?.permissions;
  const {
    'PERMISSION.ADD': add,
    'PERMISSION.UPDATE': update,
    'PERMISSION.DELETE': Delete,
  } = currUser;

  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [editModalVisible, handleEditModalVisible] = useState<boolean>(false);
  const [permissionData, setPermissionData] = useState<PermissionItem>();

  const actionRef = useRef<ActionType>();

  async function handleAdd(values: AddPermissionBean) {
    const hide = message.loading('正在添加');
    try {
      const res = await addPermission(values);
      hide();
      if (res.code == 0) {
        message.success('添加成功');
        handleAddModalVisible(false);
        actionRef.current?.reload();
      } else {
        message.error(`${res.message}`);
      }
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      handleAddModalVisible(false);
    }
  }

  async function handleEdit(values: UpdatePermissionBean) {
    const hide = message.loading('正在修改');
    try {
      const res = await editPermission(values);

      hide();
      if (res.code === SUCCESS_CODE) {
        message.success('修改成功');
        handleEditModalVisible(false);
        actionRef.current?.reload();
      } else {
        message.error(`${res.message}`);
      }
    } catch (error) {
      hide();
      message.error('修改失败请重试！');
      handleEditModalVisible(false);
    }
  }

  async function handleRemove(id: string) {
    const hide = message.loading('正在删除');
    try {
      const res = await deletePermission(id);
      hide();

      if (res.code === SUCCESS_CODE) {
        message.success('删除成功');
        handleEditModalVisible(false);
        actionRef.current?.reload();
        return true;
      }

      message.error(`${res.message}`);
      return false;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      handleEditModalVisible(false);
      return false;
    }
  }

  const columns: ProColumns<PermissionItem>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '权限名称',
      dataIndex: 'name',
    },
    {
      title: '权限识别码',
      dataIndex: 'permission_code',
      hideInSearch: true,
    },
    {
      title: '权限路由',
      dataIndex: 'route',
      hideInSearch: true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (_, record) => {
        return record.type === 1 || record.type === 0 ? '系统权限' : '自定义权限';
      },
      renderFormItem: () => {
        return (
          <Select
            options={[
              { key: '0', value: '0', label: '系统权限' },
              { key: '1', value: '1', label: '系统权限' },
              { key: '3', value: '3', label: '自定义权限' },
            ]}
          />
        );
      },
    },
    {
      title: '操作',
      hideInSearch: true,
      render: (_, record) => {
        const onClickEdit = async () => {
          handleEditModalVisible(true);
          setPermissionData(record);
        };

        const onClickRemove = () => {
          const { id, name } = record;
          Modal.confirm({
            title: `删除权限`,
            content: (
              <>
                <Divider />
                <p>确认要删除权限</p>
                <span style={{ fontWeight: 'bolder' }}>{name}</span>&nbsp;&nbsp;?
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove(id);
            },
            centered: true,
            width: '30vw',
            style: { height: '18vw' },
          });
        };

        return (
          <div>
            {update && <a onClick={onClickEdit}>修改</a>}
            <Divider type="vertical" />
            {Delete && <a onClick={onClickRemove}>删除</a>}
          </div>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<PermissionItem>
        headerTitle="权限列表"
        actionRef={actionRef}
        scroll={{ x: true }}
        search={{
          labelWidth: 'auto',
          span: { xs: 24, sm: 12, md: 8, lg: 8, xl: 8, xxl: 6 },
        }}
        pagination={{
          defaultPageSize: 10,
          size: 'default',
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        toolBarRender={() => [
          <>
            {add && (
              <Button type="primary" onClick={() => handleAddModalVisible(true)}>
                <PlusOutlined /> 添加
              </Button>
            )}
          </>,
        ]}
        tableAlertRender={() => false}
        request={(params) => {
          params.page = params.current;
          return pageQueryPermissionList(params);
        }}
        columns={columns}
        rowSelection={false}
      />
      {editModalVisible && permissionData && (
        <AuthPermissionEditForm
          permission={permissionData}
          modalVisible={editModalVisible}
          onSubmit={handleEdit}
          onCancel={() => handleEditModalVisible(false)}
        />
      )}
      {addModalVisible && (
        <AddFrom
          modalVisible={addModalVisible}
          onSubmit={handleAdd}
          onCancel={() => handleAddModalVisible(false)}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default TableList;
